package com.yanghui.dtracing.core.classLoader;

import com.yanghui.dtracing.core.PluginBootstrap;
import com.yanghui.dtracing.core.utils.AgentPackagePath;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class AgentClassLoader extends URLClassLoader {

    public static AgentClassLoader defaultClassLoader;

    private static List<URL> classpathAllJarList;

    static {
        classpathAllJarList = new ArrayList<>();
        String classpath = AgentPackagePath.getPath().toString();
        File file = new File(classpath + File.separator + "plugins");
        if(file.exists()){
            for(File child : file.listFiles()){
                if(child.isFile() && child.getName().endsWith(".jar")){
                    try {
                        classpathAllJarList.add(new URL("file:" + child.getAbsolutePath()));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static AgentClassLoader getDefault(){
        if(null == defaultClassLoader){
            synchronized(AgentClassLoader.class){
                if(null == defaultClassLoader){
                    defaultClassLoader = new AgentClassLoader(PluginBootstrap.class.getClassLoader());
                }
            }
        }
        return defaultClassLoader;
    }

    public AgentClassLoader(ClassLoader parent) {
        super(classpathAllJarList.toArray(new URL[]{}), parent);
    }
    
    public AgentClassLoader(URL[] urls,ClassLoader parent) {
        super(urls, parent);
    }
}
